package com.zcyr.controller;

import com.zcyr.constant.LoginType;
import com.zcyr.exception.GiteeLoginException;
import com.zcyr.pojo.UserInfo;
import com.zcyr.service.UserService;
import com.zcyr.util.JsonBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@CrossOrigin(allowCredentials = "true")
@RestController
@RequestMapping("login")
public class LoginController {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    HttpServletRequest request;

    @Autowired
    UserService service;


    @RequestMapping("gitee/{code}")
    public JsonBody loginByGitee(@PathVariable(value = "code") String code) {
        HttpSession session =  request.getSession();
        UserInfo userInfo;
        session.setAttribute("loginType", LoginType.GITEE);
        try {
            userInfo = service.giteeLogin(code);
            session.setAttribute("userInfo", userInfo);
        } catch (GiteeLoginException e) {
             session.invalidate(); // 释放内存中的session
            return JsonBody.error("登录失败");
        }
        logger.info(String.format("用户(%s)登录了!", userInfo.getName()));
        return JsonBody.ok("登录成功!").put("userInfo", userInfo);
    }
}
